var prefix = "/jzweb/examinationCost";
var refund = "/jzweb/refund";
var checkBatchIds = [];
var sumNum = 0;
var isNormal = 0;
var isState = 0, elInfo = '', escape = [];
$(function () {
    load();
    sessionStorage.setItem('exam_year', $('#searchYear').val())
    $('#exampleTable').bootstrapTable('hideColumn', 'year');
    $('#exampleTable').bootstrapTable('hideColumn', 'planStuNum');
    $('#exampleTable').bootstrapTable('hideColumn', 'returnStandard');
    $('#exampleTable').bootstrapTable('hideColumn', 'returnMoneySchool');
    $('#exampleTable').bootstrapTable('hideColumn', 'returnMoneyPersonal');
    $('#exampleTable').bootstrapTable('hideColumn', 'advanceDate');
    $('#moreOper').click(function () {
        alert();
    });
});

$(document).on('click', '.config-property-btn', function (e) {
    e.preventDefault(); // 阻止默认行为
    var id = $(this).data('id'); // 获取data-id
    var rowDataStr = $(this).data('list'); // 获取data-list
    var rowData = JSON.parse(decodeURIComponent(rowDataStr)); // 解码并解析JSON字符串

    // 现在你可以使用rowData对象了
    sessionStorage.setItem('ref_money', JSON.stringify(rowData))
});

function dropdownReload() {
    alert();
}

function load() {
    $('#exampleTable')
        .bootstrapTable(
            {
                method: 'get', // 服务器数据的请求方式 get or post
                url: prefix + "/list", // 服务器数据的加载地址
                //showRefresh : true,
                //showToggle : true,
                showColumns: true,
                height: 750,
                iconSize: 'outline',
                toolbar: '#exampleToolbar',
                striped: true, // 设置为true会有隔行变色效果
                dataType: "json", // 服务器返回的数据类型
                pagination: true, // 设置为true会在底部显示分页条
                singleSelect: false, // 设置为true将禁止多选
                // contentType : "application/x-www-form-urlencoded",
                // //发送到服务器的数据编码类型
                pageSize: 10, // 如果设置了分页，每页数据条数
                pageNumber: 1, // 如果设置了分布，首页页码
                pageList: [10, 25, 50, 100, 300],
                //search : true, // 是否显示搜索框
                showColumns: false, // 是否显示内容下拉框（选择显示的列）
                sidePagination: "server", // 设置在哪里进行分页，可选值为"client" 或者 "server"
                queryParamsType: "",
                // //设置为limit则会发送符合RESTFull格式的参数
                queryParams: function (params) {
                    return {
                        //说明：传入后台的参数包括offset开始索引，limit步长，sort排序列，order：desc或者,以及所有列的键值对
                        pageNumber: params.pageNumber,
                        pageSize: params.pageSize,
                        orgName: $('#searchName').val(),
                        state: $('#searchState').val(),
                        province: $('#searchProvince').val(),
                        year: $('#searchYear').val(),
                        regionUserName: $('#searchRegionUserName').val(),
                        examStartDate: $('#examStartDate').val(),
                        examEndDate: $('#examEndDate').val(),
                        isNormalNum: isNormal
                        //examinationDay:$('#searchExaminationDay').val()
                    };
                },
                // //请求服务器数据时，你可以通过重写参数的方式添加一些额外的参数，例如 toolbar 中的参数 如果
                // queryParamsType = 'limit' ,返回参数必须包含
                // limit, offset, search, sort, order 否则, 需要包含:
                // pageSize, pageNumber, searchText, sortName,
                // sortOrder.
                // 返回false将会终止请求
                responseHandler: function (res) {
                    var msg = res.msg.split(',');
                    $('#isNormalNum').html("未平账数据：" + msg[0]);
                    $('#receivablesNum').html("待收款数据：" + msg[1]);
                    return {
                        "total": res.data.total,//总数
                        "rows": res.data.records   //数据
                    };
                },
                columns: [
                    {
                        checkbox: true
                    },
                    {
                        field: 'orgName',
                        title: '学校名称'
                    },
                    {
                        field: 'year',
                        title: '年份'
                    },
                    {
                        field: 'profile',
                        title: '证书及等级',
                        formatter: function (value, row, index) {
                            var valueList = value.split(";;");
                            var html = "";
                            for (var v in valueList) {
                                html += '<div>' + valueList[v] + '</div>';
                            }
                            return html;
                        },
                        hidden: true
                    },
                    {
                        field: 'province',
                        title: '省份'
                    },
                    {
                        field: 'city',
                        title: '城市'
                    },
                    {
                        field: 'planStuNum',
                        title: '计划人数'
                    },
                    {
                        field: 'stuNum',
                        width: '85px',
                        title: '考生人数',
                        formatter: function (value, row, index) {
                            var str = "<p>计划：" + row.planStuNum + "</p>";
                            if (value == null || value == '') {
                                str += "<p>实际：-</p>";
                            } else {
                                if (Number(value) < Number(row.planStuNum))
                                    str += "<p>实际：<span style='color:cornflowerblue'>" + value + "</span></p>";
                                else if (Number(value) > Number(row.planStuNum)) {
                                    str += "<p>实际：<span style='color:green'>" + value + "</span></p>";
                                } else {
                                    str += "实际：" + value;
                                }
                            }

                            return str
                        }
                    },
                    {
                        field: 'examinationDate',
                        title: '考评日期',
                        formatter: function (value, row, index) {
                            if (value == null) return '';
                            var date = new Date(value);
                            return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
                        }
                    },
                    {
                        field: 'priceStandard',
                        width: '100px',
                        title: '费用标准',
                        formatter: function (value, row, index) {
                            if (value <= 0)
                                return "-";
                            var str = "<p>收费：" + value + "</p>";
                            str += "<p>返费：" + row.returnStandard + "</p>";
                            return str
                        }
                    },
                    {
                        field: 'receivables',
                        title: '应收款'
                    },
                    {
                        field: 'received',
                        title: '实收款',
                        formatter: function (value, row, index) {
                            if (Number(value) > Number(row.receivables)) {
                                return '<span>' + value + '</span>'
                            } else {
                                return value;
                            }
                        }
                    },
                    {
                        field: 'receivedDate',
                        title: '收款日期'
                    },
                    {
                        field: 'moneyAllDate',
                        title: '回款日期'
                    },
                    {
                        field: 'advance',
                        title: '预收款'
                    },
                    {
                        field: 'advanceDate',
                        title: '预收日期',
                        formatter: function (value, row, index) {
                            if (value == null) return '';
                            var date = new Date(value);
                            return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
                        }
                    },
                    {
                        field: 'returnStandard',
                        title: '返款标准'
                    },
                    {
                        field: 'returnMoney',
                        width: '160px',
                        title: '应返款',
                        formatter: function (value, row, index) {
                            if (value <= 0) {
                                return "暂无返款金额"
                            }
                            var str = row.updateExamine == 0 ? "<p style='color: #ff5722;font-weight: bold'>请审核，点击查看附件</p>" : ''
                            str += "<p>总额：" + value + "</p>";
                            str += "<p>学校：" + row.returnMoneySchool + "</p>";
                            str += "<p>私人：" + row.returnMoneyPersonal + "</p>";
                            return '<div class="detail-link" style="color: #0a6aa1;cursor: pointer;">' + str + '</div>'
                        }
                    }, {
                        field: 'returnSchool',
                        title: '返款学校名称'
                    },
                    {
                        field: 'returnMoneySchool',
                        title: '应返款（学校）'
                    },
                    // {
                    //     field: 'updateExamine',
                    //     title: '审核状态',
                    //     formatter: function (value, row, index) {
                    //         var str = '-'
                    //         value == 0 ? "<p style='color: red'>未审核</p>" : "<p style='color: gray'>已审核</p>";
                    //         return str
                    //     }
                    // },
                    {
                        field: 'returnMoneyPersonal',
                        title: '应返款（个人）'
                    },

                    {
                        field: 'laborWage',
                        title: '劳务费'
                    },
                    {
                        field: 'commission',
                        title: '提成'
                    },
                    {
                        field: 'regionUserName',
                        title: '负责人'
                    },
                    {
                        field: 'state',
                        title: '状态',
                        formatter: function (value, row, index) { //（0未计算，9已删除）
                            if (value == 0) {
                                return '<span class="label label-default">未开始</span>';
                            } else if (value == 1) {
                                return '<span class="label label-inverse">已考试</span>';
                            } else if (value == 2) {
                                return '<span class="label label-primary">已收款</span>';
                            } else if (value == 3) {
                                return '<span class="label label-primary">个人已返款</span>';
                            } else if (value == 4) {
                                return '<span class="label label-primary">学校已返款</span>';
                            } else if (value == 5) {
                                return '<span class="label label-success">已完成</span>';
                            } else if (value == 10) {
                                return '<span class="label label-primary">已抵扣</span>';
                            } else if (value == 11) {
                                return '<span class="label label-primary">已抵扣并收款</span>';
                            }
                        }
                    },
                    {
                        field: 'remark',
                        title: '备注'
                    },
                    {
                        title: '操作',
                        field: 'id',
                        align: 'center',
                        formatter: function (value, row, index) {
                            // var e = '<a class="btn btn-warning btn-sm '+s_edit_h+'" href="#" mce_href="#" title="编辑" onclick="edit(\''
                            // 		+ row.id
                            // 		+ '\')"><i class="fa fa-edit"></i></a>';
                            // var d = '<a class="btn btn-warning btn-sm '+s_remove_h+'" href="#" title="删除"  mce_href="#" onclick="remove(\''
                            // 		+ row.id
                            // 		+ '\')"><i class="fa fa-remove"></i></a>';
                            // var g;
                            // if(row.state!=1&&row.state!=2)
                            // 	 g = '<a class="btn  btn-default btn-sm '+s_confirmation_h+'" href="#" title="确认收款"  mce_href="#"  disabled>确认收款</a>';
                            // else
                            // 	g = '<a class="btn btn-primary btn-sm '+s_confirmation_h+' " href="#" title="确认收款"  mce_href="#" onclick="confirmationReceivable(\''
                            // 		+ row.id + '\',\''+row.receivables+'\')">确认收款</a>';
                            var s = '<button id="moreOper" class="layui-btn layui-btn-sm moreOper config-property-btn"  data-list="' + encodeURIComponent(JSON.stringify(row)) + '"  data-id="' + row.id + '"  title="更多操作" >更多操作</button>';
                            return s;
                        }
                    }],
                onClickRow: function (row, $element, field) {
                    // 获取当前行中 returnMoney 字段对应的 DOM 元素
                    var $returnMoneyElement = $element.find('.detail-link');
                    $returnMoneyElement.off('click').on('click', function (e) {
                        let data = JSON.stringify(row)
                        openDetailModal(data)
                    });
                },
                onAll: function () {
                    layui.use('dropdown', function () {
                        var dropdownData = "[";
                        if (s_edit_h == '') {
                            dropdownData += "{title:'编辑',id:'1'},";
                        }
                        if (s_remove_h == '') {
                            dropdownData += "{title:'删除',id:'2'},";
                        }
                        if (s_calc_h == '') {
                            dropdownData += "{title:'确认已考试',id:'3'},";
                        }
                        if (s_confirmation_h == '') {
                            dropdownData += "{title:'确认收款',id:'4'},";
                            dropdownData += "{title:'确认返款',id:'5'},";
                            dropdownData += "{title:'预收',id:'6'},";
                        }

                        if (refund_save == '') {
                            dropdownData += "{title:'考试费信息录入',id:'7'},";
                        }
                        if (edit_stuNum == '') {
                            dropdownData += "{title:'修改考试人数',id:'8'},";
                        }
                        if (r_offset == '') {
                            dropdownData += "{title:'返费抵考试费',id:'9'},";
                        }
                        if (s_compensation_h == '') {
                            dropdownData += "{title:'考试费抵费补款',id:'10'},";
                        }
                        dropdownData += "{title:'全部回款',id:'11'},";

                        dropdownData += "{title:'复制考试费订单',id:'12'},";
                        dropdownData += "{title:'修改返费金额',id:'13'},";
                        dropdownData += "{title:'返费金额审核',id:'14'},";
                        dropdownData = dropdownData.substring(0, dropdownData.length - 1);
                        dropdownData += "]"
                        //点击回调
                        var dropdown = layui.dropdown;
                        dropdown.render({
                            elem: '.moreOper'
                            , data: eval('(' + dropdownData + ')')
                            , click: function (data, othis) {
                                var elem = $(this.elem)
                                    , listId = elem.data('id'); //表格列表的预埋数据
                                switch (data.id) {
                                    case '1':
                                        edit(listId);
                                        break;
                                    case '2':
                                        remove(listId);
                                        break;
                                    case '3':
                                        selBatchStuNum(listId);
                                        break;
                                    case '4':
                                        confirmationReceivable(listId);
                                        break;
                                    case '5':
                                        confirmationReturn(listId);
                                        break;
                                    case '6':
                                        confirmationAdvance(listId);
                                        break;
                                    case '7':
                                        refundAdd(listId);
                                        break;
                                    case '8':
                                        editStuNum(listId);
                                        break;
                                    case '9':
                                        offset(listId);
                                        break;
                                    case '10':
                                        compensation(listId);
                                        break;
                                    case '11':
                                        fullPayment(listId);
                                        break;
                                    case '12':
                                        copyOrderForm(listId);
                                        break;
                                    case '13':
                                        editMoney(listId);
                                        break;
                                    case '14':
                                        returnMoneyExamine(listId);
                                        break;
                                }
                                //layer.msg('得到表格列表的 id：'+ listId +'，下拉菜单 id：'+ data.id);
                            }
                        });
                    })
                }
                ,
                rowStyle: function (row, index) { // 提示 标红
                    // console.log(row)
                    // console.log(Number(row.receivables) > Number(row.received))

                    if (row.isNormal == 1 || (Number(row.receivables) > Number(row.received))) {

                        return {css: {'background-color': 'red', 'border-color': 'red', 'color': 'white'}};
                    } else {
                        return {css: {}};
                    }
                }
            }
        )
    ;
}

function returnMoneyExamine(id) {
    layer.confirm('是否通过返费金额审核？', {
        title: '返费金额审核',
        skin: "my-skin", //设置自定义样式
        btn: ['同意', '拒绝'], //按钮
        btnAlign: 'c', // 按钮居中显示
    }, function () {
        $.ajax({
            url: prefix + "/updateExamine",
            type: "post",
            data: {
                'id': id,
                'status': 1
            }, success: function (r) {
                if (r.code === '0') {
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }

        });
    }, function () {
        $.ajax({
            url: prefix + "/updateExamine",
            type: "post",
            data: {
                'id': id,
                'status': 2
            }, success: function (r) {
                if (r.code === '0') {
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }

        });
    });
}

// /jzweb/examinationCost/refundMoneyLogEdit/

function editMoney(id) {
    layer.open({
        type: 2,
        title: '修改返费金额',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['800px', '70%'],
        content: '/jzweb/examinationCost/refundMoneyLogEdit/' + id // iframe的url
    });
}

function reLoad(type) {
    let examStartDate = $("#examStartDate").eq(0).val()
    let examEndDate = $("#examEndDate").eq(0).val();
    if ($("#examStartDate").eq(0).val() && $("#examEndDate").eq(0).val()) {
        $("#examStartDate").eq(0).val('');
        $("#examEndDate").eq(0).val('')
        $("#examStartDate").eq(0).val(examStartDate + ' 00:00:00');
        $("#examEndDate").eq(0).val(examEndDate + ' 23:59:59');
    }

    if (type == 1) {
        isNormal = (isNormal + 1) % 2;
    }
    if (type == 2) {
        isState = (isState + 1) % 2;
        if (isState == 1)
            $('#searchState').val(1);
        else $('#searchState').val(null);
    }

    $('#exampleTable').bootstrapTable('refresh');
}

//确认已考试，计算相关费用
function selBatchStuNum(id) {
    escape = [];
    // layer.prompt({
    // 		formType: 0,
    // 		title: '请输入考试人数'},
    // 	function (value,index,elem) {
    // 		var reg = /^[0-9]+\.?[0-9]*$/;
    // 		if (reg.test(value)) {
    // 			value = parseFloat(value);
    $.ajax({
        url: prefix + "/selBatchStuNum",
        type: "post",
        data: {
            'id': id
        },
        success: function (r) {
            if (r.code == 0) {
                checkBatchIds = [];
                sumNum = 0;
                startTime = null;
                var str = "<p>对应考试批次如下，请确认数据无误：</p>";
                var totle = 0;
                for (var i in r.data) {
                    totle += Number(r.data[i].stuNum);
                    str += `<p>
										<input type='checkbox' data-tips="${r.data[i].name}" id='${r.data[i].id}' onclick="checkBatch(${i},${r.data[i].stuNum},this,event)">${(Number(i) + 1)}.${r.data[i].name}（人数：${r.data[i].stuNum}）</p>`;
                }
                //var start=r.data[0].startTime;
                str += "<p id='sumNum'>总人数：0</p>";
                str += "<br/><p style='color:#ff2222;font-weight: 400;'>数据如有问题，请联系系统管理员</p>";
                str += "<div class='loading' style='position: absolute;top: 50%;left: 45%;width: 64px;height: 64px;transform: translate(-50%,-50%);animation: loading .8s infinite; display: none;'><img src='../../../../img/loading.png' style='width: 100%'></div>";
                layer.open({
                    type: 1
                    ,
                    title: false //不显示标题栏
                    ,
                    closeBtn: false
                    ,
                    area: '600px;'
                    ,
                    shade: 0.8
                    ,
                    id: 'LAY_layuipro' //设定一个id，防止重复弹出
                    ,
                    btn: ['确认', '取消']
                    ,
                    btnAlign: 'c'
                    ,
                    moveType: 1 //拖拽模式，0或者1
                    ,
                    content: '<div class="checkedInput" style="position: relative;padding: 25px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">' + str + '</div>'
                    ,
                    yes: function (index) {
                        if (checkBatchIds.length <= 0) {
                            layer.msg("请勾选对应的考试批次！");
                            return;
                        }
                        var start = r.data[checkBatchIds.sort()[0]].startTime;
                        var costBatchId = '';
                        let newescape = escape.filter(function (ev) {
                            return ev != null;
                        })
                        costBatchId = newescape.join();
                        $(".loading").show();
                        $.ajax({
                            url: prefix + "/calculate",
                            type: "post",
                            data: {
                                'id': id,
                                'stuNum': sumNum,
                                'start': start,
                                'batchName': elInfo,
                                'costBatchId': costBatchId
                            },
                            success: function (data) {
                                //layer.msg(data.msg);
                                //layer.close(index);
                                elInfo = '';
                                escape = [];
                                //reLoad();
                                $(".loading").hide();
                                if (data.code == 0) {
                                    layer.msg(data.msg);
                                    $('#exampleTable').bootstrapTable('refresh');
                                    reLoad();
                                } else if (data.code == 41304) {
                                    layer.confirm('是否下载错误报告？', {
                                        btn1: function (index) {
                                            window.location.href = '/jzweb/examinationCost/importcalculateError';
                                            layer.close(index)
                                            reLoad();
                                        }
                                    });
                                } else {
                                    layer.msg(data.msg);
                                }
                            }
                        })
                    }
                });
            } else {
                layer.open({
                    title: '提示'
                    , content: r.msg
                });
            }
        }
    });
}

function checkBatch(batchId, stuNum, that, ev) {
    if (ev.target.checked) {
        escape[batchId] = $(that).attr('id');
    } else {
        escape[batchId] = null;
    }
    elInfo += $(that).attr('data-tips');

    if (checkBatchIds.indexOf(batchId) == -1) {
        checkBatchIds.splice(checkBatchIds.length, 0, batchId);
        sumNum += stuNum;
        // elInfo
    } else {
        checkBatchIds.splice(checkBatchIds.indexOf(batchId), 1);
        sumNum -= stuNum;
    }
    $("#sumNum").html("总人数:" + sumNum);
}

function calculate(id, totle) {

}

//新增
function add() {
    layer.open({
        type: 2,
        title: '增加',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['800px', '70%'],
        content: prefix + '/add' // iframe的url
    });
}

function edit(id) {
    layer.open({
        type: 2,
        title: '编辑',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['800px', '70%'],
        content: prefix + '/edit/' + id // iframe的url
    });
}

// 打开详情弹窗
function openDetailModal(rowData) {
    const data = JSON.parse(rowData)
    $.ajax({
        url: '/jzweb/examinationCost/selRefundMoneyLog',
        type: "GET",
        data: {
            'id': data.id
        }, success: function (r) {
            console.log(r)
            let content = '';
            r.data.forEach((item, index) => {
                content += `
                            <div style="padding:20px;border: 1px dashed skyblue;margin-top: 10px">
                                 <div class="form-box" style="padding-bottom: 10px">
                                     <label style="width: 150px;">修改时间：</label>
                                     <div class="layui-input-inline">
                                         <input disabled id="name${index}" name="name${index}" value="${item.createDate}" type="text" required lay-verify="required" class="form-control" placeholder="暂无">
                                     </div>
                                </div>
                                <div class="form-box" style="padding-bottom: 10px">
                                     <label style="width: 150px;">对公修改前金额：</label>
                                     <div class="layui-input-inline">
                                         <input disabled id="name${index}" name="name${index}" value="${item.dgUpdateMoneyBefore}" type="text" required lay-verify="required" class="form-control" placeholder="暂无">
                                     </div>
                                </div>
                                <div class="form-box" style="padding-bottom: 10px">
                                     <label style="width: 150px;">对公修改后金额：</label>
                                     <div class="layui-input-inline">
                                         <input disabled id="name${index}" name="name${index}" value="${item.dgUpdateMoneyLater}" type="text" required lay-verify="required" class="form-control" placeholder="暂无">
                                     </div>
                                </div>
                                 <div class="form-box" style="padding-bottom: 10px">
                                     <label style="width: 150px;">对私修改前金额：</label>
                                     <div class="layui-input-inline">
                                         <input disabled id="name${index}" name="name${index}" value="${item.dsUpdateMoneyBefore}" type="text" required lay-verify="required" class="form-control" placeholder="暂无">
                                     </div>
                                </div>
                                <div class="form-box" style="padding-bottom: 10px">
                                     <label style="width: 150px;">对私修改后金额：</label>
                                     <div class="layui-input-inline">
                                         <input disabled id="name${index}" name="name${index}" value="${item.dsUpdateMoneyLater}" type="text" required lay-verify="required" class="form-control" placeholder="暂无">
                                     </div>
                                </div>
                                <div class="form-box" style="padding-bottom: 10px">
                                     <label style="width: 150px;">备注：</label>
                                     <div class="layui-input-inline">
                                         <input disabled id="name${index}" name="name${index}" value="${item.remark}" type="text" required lay-verify="required" class="form-control" placeholder="暂无">
                                     </div>
                                </div>
                                <div class="form-box" style="padding-bottom: 10px">
                                     <label style="width: 150px;">凭证文件：</label>
                                     <div class="layui-input-inline">
                                        <a href="${item.file}" style="color: #0a6aa1">点击查看</a>
                                     </div>
                                </div>
                            </div>
                        `;
            });

            layer.open({
                type: 1,
                title: '详细信息',
                maxmin: true,
                shadeClose: false, // 点击遮罩关闭层
                area: ['600px', '600px'],
                content: `
                <div style="padding: 20px">
                     ${content}
                </div>
        `
            });
        }
    });

}

//抵费补款
function compensation(id) {
    layer.prompt({
            formType: 0,
            title: '请输入补费金额'
        },
        function (value, index, elem) {
            var reg = /^[0-9]+\.?[0-9]*$/;
            if (reg.test(value)) {
                value = parseFloat(value);
                $.ajax({
                    url: prefix + "/compensation",
                    type: "get",
                    data: {
                        'id': id,
                        'cost': value
                    },
                    success: function (r) {
                        if (r.code == 0) {
                            layer.msg(r.msg);
                            layer.close(index);
                            reLoad();
                        } else {
                            layer.msg(r.msg);
                            reLoad();
                        }
                    }
                });

            } else {
                layer.msg('非法输入', function () {
                });
            }

        })
}

/**
 * 全部回款
 * */
function fullPayment(id) {
    layer.confirm('是否全部回款？', {
        btn: ['确定', '取消'], // 按钮
        icon: 3, // 图标
        title: '确认操作' // 标题
    }, function (index) {
        paymentAll(id)
        layer.close(index);
    }, function (index) {
        layer.close(index)
    });
}

function paymentAll(id) {
    $.ajax({
        url: prefix + "/confirmationReceivableAll",
        type: "post",
        data: {
            'id': id
        }, success: function (r) {
            if (r.code === '0') {
                layer.msg(r.msg);
                reLoad();
            } else {
                layer.msg(r.msg);
            }
        }

    });
}

/**
 * 复制考试费订单
 * */
function copyOrderForm(id) {
    layer.confirm('是否复制该订单数据？', {
        btn: ['确定', '取消'], // 按钮
        icon: 3, // 图标
        title: '确认操作' // 标题
    }, function (index) {
        copyOrderDate(id)
        layer.close(index);
    }, function (index) {
        layer.close(index)
    });
}

function copyOrderDate(id) {
    $.ajax({
        url: prefix + `/exCostCopy?id=${id}`,
        type: "get",
        success: function (r) {
            if (r.code === '0') {
                layer.msg(r.msg);
                reLoad();
            } else {
                layer.msg(r.msg);
            }
        }

    });
}


function offset(id) {
    layer.open({
        type: 2,
        title: '返费抵考试费',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['800px', '520px'],
        content: prefix + '/offset/' + id // iframe的url
    });
}


function editStuNum(id) {
    layer.prompt({
            formType: 0,
            title: '请输入考试人数'
        },
        function (value, index, elem) {
            var reg = /^[0-9]+\.?[0-9]*$/;
            if (value <= 0) {
                layer.msg('考试人数必须大于0！', function () {
                });
                return false;
            }
            if (reg.test(value)) {
                value = parseFloat(value);
                $.ajax({
                    url: prefix + "/editStuNum",
                    type: "post",
                    data: {
                        'id': id,
                        'stuNum': value
                    },
                    success: function (r) {
                        if (r.code == 0) {
                            layer.msg(r.msg);
                            layer.close(index);
                            reLoad();
                        } else {
                            layer.msg(r.msg);
                            reLoad();
                        }
                    }
                });

            } else {
                layer.msg('非法输入', function () {
                });
            }

        })
}

function confirmationAdvance(id) {
    layer.prompt(
        // {
        // 	formType: 0,
        // 	title: '请输入预收金额'},
        function (value, index, elem) {
            var reg = /^[0-9]+\.?[0-9]*$/;
            // if(value<=0){
            // 	layer.msg('金额必须大于0！', function () {
            // 	});
            // 	return false;
            // }
            if (reg.test(value)) {
                value = parseFloat(value);
                $.ajax({
                    url: prefix + "/confirmationAdvance",
                    type: "post",
                    data: {
                        'id': id,
                        'advance': value
                    },
                    success: function (r) {
                        if (r.code == 0) {
                            layer.msg(r.msg);
                            layer.close(index);
                            reLoad();
                        } else {
                            layer.msg(r.msg);
                            reLoad();
                        }
                    }
                });

            } else {
                layer.msg('非法输入', function () {
                });
            }

        })
}

function refundAdd(id) {

    $.ajax({
        url: refund + "/list",
        type: "get",
        data: {
            'id': id
        },

    });
}

//确认收款
function confirmationReceivable(id) {
    layer.prompt(
        // {
        // formType: 0,
        // title: '请输入实际收款金额'},
        function (value, index, elem) {
            var reg = /^[0-9]+\.?[0-9]*$/;
            if (reg.test(value)) {
                value = parseFloat(value);
                $.ajax({
                    url: prefix + "/confirmationReceivable",
                    type: "post",
                    data: {
                        'id': id,
                        'received': value
                    },
                    success: function (r) {
                        if (r.code == 0) {
                            layer.msg(r.msg);
                            layer.close(index);
                            reLoad();
                        } else {
                            layer.msg(r.msg);
                            reLoad();
                        }
                    }
                });

            } else {
                layer.msg('非法输入', function () {
                });
            }

        })
}

//确认返款
function confirmationReturn(id) {
    layer.open({
        type: 2,
        title: '编辑',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['400px', '240px'],
        content: prefix + '/confirmationReturn?id=' + id // iframe的url
    });
}

function remove(id) {
    layer.confirm('确定要删除选中的记录？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: prefix + "/remove",
            type: "post",
            data: {
                'id': id
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}

function resetPwd(id) {
}

function batchRemove() {
    var rows = $('#exampleTable').bootstrapTable('getSelections'); // 返回所有选择的行，当没有选择的记录时，返回一个空数组
    if (rows.length == 0) {
        layer.msg("请选择要删除的数据");
        return;
    }
    layer.confirm("确认要删除选中的'" + rows.length + "'条数据吗?", {
        btn: ['确定', '取消']
        // 按钮
    }, function () {
        var ids = new Array();
        // 遍历所有选择的行数据，取每条数据对应的ID
        $.each(rows, function (i, row) {
            ids[i] = row['id'];
        });
        $.ajax({
            type: 'POST',
            data: {
                "ids": ids
            },
            url: prefix + '/batchRemove',
            success: function (r) {
                if (r.code == 0) {
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    }, function () {

    });
}

//导入
function importExcel(fileObj, formObj, url) {
    var loading = layer.load(1, {
        shade: [0.1, '#fff'] //0.1透明度的白色背景
    });
    var fileUrl = fileObj.val();
    var suffix = fileUrl.substr(fileUrl.lastIndexOf(".")).toLowerCase();//获得文件后缀名
    if (suffix == '.xls' || suffix == '.xlsx') {
        if (fileUrl) {
            formObj.ajaxSubmit({
                type: "post",
                url: url,
                data: {},
                dataType: "json",
                success: function (data) {
                    if (data.code == 0) {
                        layer.close(loading);
                        layer.msg("操作成功");
                        reLoad();
                    } else if (data.code == 41304) {
                        layer.confirm('是否下载错误报告？', {
                            btn1: function (index) {
                                window.location.href = '/jzweb/examinationCost/importError';
                                layer.close(index);
                                layer.close(loading);
                            },
                            btn2: function (index) {
                                layer.close(loading);
                                $('#exampleTable').bootstrapTable('refresh');
                            }
                        });
                    } else {
                        layer.msg(data.msg);
                    }
                }, error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.msg('出错了!');
                }
            });
        } else {
            layer.msg('上传的文件不可为空');
            // parent.$.messager.alert('警告', "上传的文件不可为空", 'warning');
        }
    } else {
        layer.msg('请上传正确的Excel表格!');
        // $.messager.alert('警告', "", 'warning');
    }
}

var prefix = "/jzweb/examinationCost";
$(function () {
    //学校查询
    $('#orgName').selectPage({
        showField: 'name',
        keyField: 'name',
        data: prefix + '/selectSchool',
        //向服务端提交的参数中，增加已选中的
        //设置返回-1，意为通知服务端返回空列表，初始化时使用
        params: function () {
            var pv = $('#orgName').val();
            return pv;
        },
        eAjaxSuccess: function (d) {
            console.log(d)
            var result;
            if (d) result = d.data;
            else result = undefined;
            return result;
            add.js
        }
    });

});
